package com.csdj.common.aop;

import com.csdj.common.WebResult;
import com.csdj.common.annnation.Roles;
import com.csdj.common.constant.WebResultConstant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

public abstract class AbstractRoleParase {

    private Logger log = LoggerFactory.getLogger("roleparaser");

    @Pointcut("@annotation(com.csdj.common.annnation.Roles)")
    public void pointcut(){}


    @Around("pointcut()")
    public Object roleCheck(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        Roles roles = methodSignature.getMethod().getAnnotation(Roles.class);
        if(checkRole(roles.value())){
            return pjp.proceed();
        }else{
            final Class returnType = methodSignature.getReturnType();
            log.info(returnType.getName());
            //根据返回类型

            //webresult
            if(returnType.getName().equals(WebResult.class.getName())){
                return WebResult.fail(WebResultConstant.NO_AUTH);
            }
            //modelandview
            if(returnType.getName().equals("org.springframework.web.servlet.ModelAndView")){
                final Class<?> mav = Class.forName("org.springframework.web.servlet.ModelAndView");
                Object obj = mav.newInstance();
                Method method = mav.getMethod("setViewName", String.class);
                method.invoke(obj,getLoginUrl());
                return obj;
            }
            //字符串
            if(returnType.getName().equals(String.class.getName())){
                return getLoginUrl();
            }
            return getLoginUrl();
        }
    }

    public abstract boolean checkRole(String[] roles);

    public abstract String getLoginUrl();

}
